/*
 * @Author: FightWz
 * @Date: 2019-10-10 13:21:52
 * @LastEditors: wuzhen
 * @LastEditTime: 2019-10-11 10:30:46
 * @Description: FightWz
 */
import { getToken } from "@/config/auth";
let Socket = "";
let setIntervalWesocketPush = null;
const token = getToken();
const wsUrl =
  "ws://192.168.0.240:5005/transporter/admin?token=" +
  token.split("Bearer ")[1];

// 建立连接
export function createSocket() {
  if ("WebSocket" in window) {
    if (!Socket) {
      console.log("建立websocket连接");
      Socket = new WebSocket(wsUrl);
      Socket.onopen = onopenWS;
      Socket.onmessage = onmessageWS;
      Socket.onerror = onerrorWS;
      Socket.onclose = oncloseWS;
    } else {
      console.log("websocket已连接");
    }
  } else {
    alert("当前浏览器 Not support websocket");
  }
}

// 打开WS之后发送心跳
export function onopenWS() {
  sendPing(); //发送心跳
}
// 连接失败重连
export function onerrorWS() {
  clearInterval(setIntervalWesocketPush);
  Socket.close();
  createSocket(); //重连
}

// WS数据接收统一处理
export function onmessageWS(e) {
  window.dispatchEvent(
    new CustomEvent("onmessageWS", {
      detail: {
        data: e
      }
    })
  );
}

// 发送数据
export function sendWSPush(eventTypeArr) {
  const obj = {
    appId: "airShip",
    cover: 0,
    event: eventTypeArr
  };
  if (Socket !== null && Socket.readyState === 3) {
    Socket.close();
    createSocket(); //重连
  } else if (Socket.readyState === 1) {
    Socket.send(JSON.stringify(obj));
  } else if (Socket.readyState === 0) {
    setTimeout(() => {
      Socket.send(JSON.stringify(obj));
    }, 3000);
  }
}

// 关闭WS
export function oncloseWS() {
  clearInterval(setIntervalWesocketPush);
  Socket = "";
  console.log("websocket已断开");
}

// 发送心跳
export function sendPing() {
  const obj = {
    cmd: "heartbeat"
  };
  setIntervalWesocketPush = setInterval(() => {
    Socket.send(JSON.stringify(obj));
  }, 15000);
}
